package cn.com.zero.db.config;

import cn.com.zero.db.aspect.DataSourceAOP;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * @author liuxh
 * @version 1.0.0
 * @Description
 * @createTime 2022/7/14 17:53
 */
@Configuration
@Import(DataSourceAOP.class)
@AutoConfigureBefore(value = {DruidDataSourceAutoConfigure.class}) // 在springboot的数据源自动配置bean对象之前先构建对象
@ConditionalOnProperty(name = {"spring.datasource.dynamic.enable"}, matchIfMissing = false, havingValue = "true")
public class DynamicDataSourceConfig {

    /**
     * 动态数据源 仅一个
     */
    @Primary
    @Bean
    public DynamicDataSource dynamicDataSource() {
        return new DynamicDataSource();
    }

    /**
     * 事务管理器
     */
    @Bean
    public PlatformTransactionManager transactionManager(DynamicDataSource dynamicDataSource) {
        return new DataSourceTransactionManager(dynamicDataSource);
    }
}
